package com.cheng.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.cheng.bos.actionUtils.ActionUtils;
import com.cheng.bos.pinyin4jUtils.pinyin4jUtils;
import com.cheng.domain.base.Area;
import com.cheng.domain.base.FixedArea;
import com.cheng.domain.base.SubArea;
import com.cheng.service.base.SubAreaService;
import com.opensymphony.xwork2.ActionContext;

@Namespace("/subarea")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class SubAreaAction extends ActionUtils<SubArea> {
	
	@Autowired
	private SubAreaService subAreaService;
	
	@Action(value="subarea_save",results={@Result(name="success",type="redirect",location="../pages/base/sub_area.html")})
	public String saveSubArea(){
		subAreaService.saveSubArea(model);
		return SUCCESS;
	}
	
	//属性驱动获取id
	private String ids;
	public void setIds(String ids) {
		this.ids = ids;
	}
	
	@Action(value="subarea_del",results={@Result(name="success",type="redirect",location="../../pages/base/sub_area.html")})
	public String deleteSubArea(){
		if (ids != null && !"".equals(ids) ) {
			String[] str = ids.split(",");
			for (String id : str) {
				subAreaService.deleteSubArea(id);
			}
		}
		return SUCCESS;
	}
	
	
	@Action(value="subarea_pagesearch",results={@Result(name="success",type="json")})
	public String searchSubArea(){
		Pageable pageable = new PageRequest(page-1,rows);
		Specification<SubArea> specification = new Specification<SubArea>() {
			
			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
					Join<Object, Object> rootarea = root.join("area",JoinType.INNER);
					if (model.getArea() != null && model.getArea().getProvince() != null) {
						Predicate p1 = cb.like(rootarea.get("province"), "%"+model.getArea().getProvince()+"%");
						list.add(p1);
					}
					if (model.getArea() != null && model.getArea().getCity() != null) {
						Predicate p2 = cb.like(rootarea.get("city"), "%"+model.getArea().getCity()+"%");
						list.add(p2);
					}
					if (model.getArea() != null && model.getArea().getDistrict() != null) {
						Predicate p3 = cb.like(rootarea.get("district"), "%"+model.getArea().getDistrict()+"%");
						list.add(p3);
					}
					if(model.getKeyWords() != null){
						Predicate p4 = cb.like(root.get("keyWords").as(String.class), "%"+model.getKeyWords()+"%");
						list.add(p4);
					}
					
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<SubArea> pageData = subAreaService.searchSubArea(specification,pageable);
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
	//属性驱动获取定区id
	private String fixedareaid;
	
	public void setFixedareaid(String fixedareaid) {
		this.fixedareaid = fixedareaid;
	}
	//获取指定定区的分区
	@Action(value="fixedarea_subarea",results={@Result(name="success",type="json")})
	public String getassociationSubarea(){
		Specification<SubArea> specification = new Specification<SubArea>() {
			
			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				Join<Object, Object> rootjoin = root.join("fixedArea");
				return cb.equal(rootjoin.get("id").as(String.class),fixedareaid);
			}
		};
		
		List<SubArea> list = subAreaService.getgetassociationSubarea(specification);
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	//属性注入
	private File file;
	private String fileFileName;
	
	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	@Action(value="addsubareas",results={@Result(name="success",type="redirect",location="../pages/base/sub_area.html")})
	public String saveSubAreas(){
		List<SubArea> subareas = new ArrayList<SubArea>();
		if (fileFileName.endsWith(".xls")) {
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
				HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
				for (Row row : sheet) {
					SubArea subarea = new SubArea();
					FixedArea fixedArea = new FixedArea();
					Area area = new Area();
					if (row.getRowNum()==0) {
						continue;
					}
					if (row.getCell(0)==null ||StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
						continue;
					}
					subarea.setId(row.getCell(0).getStringCellValue());
					fixedArea.setId(row.getCell(1).getStringCellValue());
					subarea.setFixedArea(fixedArea);
					area.setId(row.getCell(2).getStringCellValue());
					subarea.setArea(area);
					subarea.setKeyWords(row.getCell(3).getStringCellValue());
					subarea.setStartNum(row.getCell(4).getStringCellValue());
					subarea.setEndNum(row.getCell(5).getStringCellValue());
					subarea.setSingle(row.getCell(6).getStringCellValue().charAt(0));
					subarea.setAssistKeyWords(row.getCell(7).getStringCellValue());
					subareas.add(subarea);
				}
				subAreaService.saveAreas(subareas);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	@Action(value="downfile")
	public void downloadArea(){
		List<SubArea> list = subAreaService.findAllArea();
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("区域信息");
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("分区编号");
		row.createCell(1).setCellValue("定区编码");
		row.createCell(2).setCellValue("区域编码");
		row.createCell(3).setCellValue("关键字");
		row.createCell(4).setCellValue("起始号");
		row.createCell(5).setCellValue("结束号");
		row.createCell(6).setCellValue("单双号");
		row.createCell(7).setCellValue("位置信息");
		for (int i = 0; i < list.size(); i++) {
			HSSFRow rowtem = sheet.createRow(i+1);
			rowtem.createCell(0).setCellValue(list.get(i).getId());
			rowtem.createCell(1).setCellValue(list.get(i).getFixedArea().getId());
			rowtem.createCell(2).setCellValue(list.get(i).getArea().getId());
			rowtem.createCell(3).setCellValue(list.get(i).getKeyWords());
			rowtem.createCell(4).setCellValue(list.get(i).getStartNum());
			rowtem.createCell(5).setCellValue(list.get(i).getEndNum());
			rowtem.createCell(6).setCellValue(list.get(i).getSingle());
			rowtem.createCell(7).setCellValue(list.get(i).getAssistKeyWords());
		}
		//定义文件名称
		String fileName = "subarea.xls";
		//设置头信息
		HttpServletResponse response = ServletActionContext.getResponse();
		//disponsition浏览器以附件形式打开
		response.setHeader("content-disposition", "attachment;filename="+fileName);
		//设置文件格式
		String mimeType = ServletActionContext.getServletContext().getMimeType(fileName);
		response.setContentType(mimeType);
		//将输出流对接
		try {
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
